<template>
  <el-form
    :model="formData"
    ref="formRef"
    :rules="formRules"
    label-width="80px"
    @submit.prevent
  >
    <el-form-item label="公司名称" prop="companyName">
      <el-input
        v-model.trim="formData.companyName"
        class="width-custom"
      ></el-input>
    </el-form-item>
    <el-form-item label="备注" prop="companyDesc">
      <el-input
        type="textarea"
        :rows="2"
        placeholder="请输入内容"
        v-model="formData.companyDesc"
        class="width-custom"
      ></el-input>
    </el-form-item>
  </el-form>

  <el-row justify="end">
    <el-button @click="handleSubmit(false)">取 消</el-button>
    <el-button type="primary" @click="handleSubmit(true)">确 定</el-button>
  </el-row>
</template>

<script lang="ts">
import { reactive, defineComponent, toRefs, ref, toRef } from "vue";
import { cloneDeep } from "lodash-es";
// @ts-ignore
import { postSysCompanyAdd, postSysCompanyUpdate } from "/@/api/organization";
// @ts-ignore
import NotifMessage from "/@/utils/message/notification";

export default defineComponent({
  emits: ["emitSubmit"],
  props: {
    mode: {
      type: String,
      require: true,
      default: "add"
    },
    companyInfo: {
      type: Object,
      default: () => {}
    }
  },
  setup(props, { emit }) {
    const formRef = ref<HTMLFormElement | null>(null) as any;
    const currentInfo = toRef(props, "companyInfo");

    let state = reactive({
      formData: {
        companyName: "",
        companyDesc: ""
      }
    });

    const formRules = ref({
      companyName: [
        { required: true, message: "请输入公司名称", trigger: "blur" }
      ]
    });

    if (props.mode === "edit") {
      const copyCurrentInfo = cloneDeep(currentInfo.value);
      state.formData = copyCurrentInfo;
    }

    // 确认提交或者取消
    const handleSubmit = async (isSubmit): Promise<void> => {
      if (isSubmit) {
        const isValid = await new Promise(resolve =>
          formRef.value.validate(resolve)
        );
        if (!isValid) return;

        if (props.mode === "edit") {
          const { code, message } = await postSysCompanyUpdate(state.formData);
          requestSuccess(code, message, isSubmit);
        } else {
          const { code, message } = await postSysCompanyAdd(state.formData);
          requestSuccess(code, message, isSubmit);
        }
      } else {
        emit("emitSubmit", isSubmit);
      }
    };

    // 统一处理请求结果方法
    const requestSuccess = (
      code: number,
      message: string,
      isSubmit: boolean
    ) => {
      if (code === 200) {
        NotifMessage.success(message);
        emit("emitSubmit", isSubmit);
      }
    };

    return {
      ...toRefs(state),
      formRef,
      formRules,
      handleSubmit
    };
  }
});
</script>
